{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Stock Market Tracker - Multi-step Agent in a single prompt\n",
    "\n",
    "This notebook shows how **easy** it is to build a multi-step agent using a single prompt with aisuite + MCP tools.\n",
    "\n",
    "**What it does**: 1. Fetches latest stock market data, 2. Analyzes content and 3. Creates an HTML dashboard.\n",
    "\n",
    "**Requirements**: `OPENAI_API_KEY` in your `.env` file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Ready!\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from datetime import datetime\n",
    "from dotenv import load_dotenv\n",
    "import aisuite as ai\n",
    "from aisuite.mcp import MCPClient\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "# Initialize MCP servers for web fetching and file writing\n",
    "fetch_mcp = MCPClient(command=\"uvx\", args=[\"mcp-server-fetch\"])\n",
    "filesystem_mcp = MCPClient(\n",
    "    command=\"npx\",\n",
    "    args=[\"-y\", \"@modelcontextprotocol/server-filesystem\", os.getcwd()]\n",
    ")\n",
    "\n",
    "print(\"✓ Ready!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Craft instructions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✓ Agent instructions defined\n"
     ]
    }
   ],
   "source": [
    "# Define what you want the agent to do\n",
    "prompt = f\"\"\"Create a stock market dashboard for {datetime.now().strftime('%Y-%m-%d')}.\n",
    "\n",
    "**⚠️ EXECUTION RULES:**\n",
    "- Execute ALL tools silently (no intermediate text responses)\n",
    "- Write the HTML file FIRST, then provide summary\n",
    "- If you respond with text before writing the file, the loop stops!\n",
    "\n",
    "**TASK:**\n",
    "\n",
    "1. **Fetch Stock Data**\n",
    "   - Get top gainers from: https://finance.yahoo.com/markets/stocks/gainers/\n",
    "   - Extract: ticker, company name, price, % change\n",
    "   - Get 3-5 stocks\n",
    "\n",
    "2. **Create Professional HTML Dashboard**\n",
    "   - Title: \"Stock Market Movers - {datetime.now().strftime('%B %d, %Y')}\"\n",
    "   - Display top gainers in a clean table or card layout\n",
    "   - Use green color for positive % changes\n",
    "   - Add professional styling:\n",
    "     * Modern typography\n",
    "     * Shadows and borders\n",
    "     * Responsive design\n",
    "     * Clean spacing\n",
    "   - Include timestamp and data source\n",
    "\n",
    "3. **Save File**\n",
    "   - Use write_file to save as 'stock_dashboard.html'\n",
    "   - Confirm successful write\n",
    "\n",
    "4. **Respond**\n",
    "   - ONLY after file is written, provide a brief summary\n",
    "   - Include: number of stocks, top 3 gainers with % changes\n",
    "\n",
    "Make it look like a professional financial dashboard!\"\"\"\n",
    "\n",
    "print(\"✓ Agent instructions defined\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run Agent with MCP tools."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "============================================================\n",
      "✓ DASHBOARD CREATED!\n",
      "============================================================\n",
      "\n",
      "The stock market dashboard for November 11, 2025, has been successfully created and saved as 'stock_dashboard.html'. It displays the top 5 stock gainers with a professional layout. Here are the top 3 gainers:\n",
      "\n",
      "1. **Cogent Biosciences, Inc. (COGT)** - +119.03%\n",
      "2. **Navitas Semiconductor Corporation (NVTS)** - +22.45%\n",
      "3. **Opendoor Technologies Inc. (OPEN)** - +21.77%\n",
      "\n",
      "The dashboard includes modern typography, responsive design, and highlights positive percentage changes in green.\n"
     ]
    }
   ],
   "source": [
    "# Create agent and run it\n",
    "client = ai.Client()\n",
    "tools = fetch_mcp.get_callable_tools() + filesystem_mcp.get_callable_tools()\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=\"openai:gpt-4o\",\n",
    "    messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "    tools=tools,\n",
    "    max_turns=20\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"✓ DASHBOARD CREATED!\")\n",
    "print(\"=\"*60)\n",
    "print(f\"\\n{response.choices[0].message.content}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## View Dashboard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"900\"\n",
       "            height=\"600\"\n",
       "            src=\"stock_dashboard.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x114517b60>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "💡 Open 'stock_dashboard.html' in your browser for full view\n"
     ]
    }
   ],
   "source": [
    "from IPython.display import IFrame, display\n",
    "\n",
    "if os.path.exists('stock_dashboard.html'):\n",
    "    display(IFrame(src='stock_dashboard.html', width=900, height=600))\n",
    "    print(\"\\n💡 Open 'stock_dashboard.html' in your browser for full view\")\n",
    "else:\n",
    "    print(\"⚠️ Dashboard not created - check the output above\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cleanup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fetch_mcp.close()\n",
    "filesystem_mcp.close()\n",
    "print(\"✓ Done! That's how easy it is to build an agent with aisuite.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## That's It!\n",
    "\n",
    "In just **few lines of code**, you built an autonomous agent that:\n",
    "- ✅ Fetches live stock data from the web\n",
    "- ✅ Creates a beautiful HTML dashboard\n",
    "- ✅ Saves it to disk\n",
    "\n",
    "**Try it yourself**:\n",
    "- Modify the prompt to fetch TOP losers and gainers.\n",
    "- Modify to fetch data across multiple days.\n",
    "- Modify to fetch headlines from any Finance News website to explain why stocks rose or fell. (NOTE: Many websites do not like automated calls - be mindful of their policies.)\n",
    "- Try asking Agent to plot a graph with the data in the HTML page.\n",
    "- Add more MCP tools (memory, search, etc.)\n",
    "\n",
    "Remember to **increase max_turns** to a higher number if you increase the complexity of the tasks.\n",
    "\n",
    "**Learn more**: Check out other notebooks in `examples/agents/`"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
